# -*- coding: utf-8 -*-
import glob, os, re

def retrieve(topic: str, top_k: int = 3, data_dir: str = "data/knowledge") -> str:
    """
    极简离线检索：对 data/knowledge/*.md 进行关键词计分，取 top_k 段落拼接。
    你可以把摘要+出处直接写在 md 文件里。
    """
    toks = [w for w in re.split(r"\W+", topic) if len(w) >= 2]
    files = glob.glob(os.path.join(data_dir, "*.md"))
    scored = []
    for fp in files:
        try:
            txt = open(fp, "r", encoding="utf-8").read()
        except:
            continue
        score = sum(txt.count(t) for t in toks)
        scored.append((score, fp, txt))
    scored.sort(reverse=True, key=lambda x: x[0])
    pieces = []
    for _, fp, txt in scored[:max(1, top_k)]:
        pieces.append(f"【来源：{os.path.basename(fp)}】\n" + txt.strip()[:1200])
    return "\n\n".join(pieces) if pieces else ""
